<template>
    <div>
        <Layout class-prefix="tally">
            <Type class="type-tab" :type="type" v-on:update:type="selectType($event)"/>
            <div class="tally-operations">
                <div class="tally-options">
                    <Amount :type="type" :amountValue="amountValue" :expression="expression"/>
                    <Category :type="type" :category="selectedCategory" v-on:update:category="selectedCategory=$event"/>
                    <DatePicker :selectedDate="selectedDate" v-on:update:date="selectedDate = $event"/>
                    <Notes :type="type" :notes="notes" v-on:update:notes="notes=$event"/>
                </div>
                <NumberPad v-on:update:content="changeAmount($event)"/>
            </div>
        </Layout>
    </div>
</template>

<script lang="ts">
    import Type from '@/components/Type.vue';
    import Amount from '@/components/Amount.vue';
    import Category from '@/components/Category.vue';
    import Notes from '@/components/Notes.vue';
    import NumberPad from '@/components/NumberPad.vue';
    import DatePicker from '@/components/DatePicker.vue'
    import Vue from 'vue';
    import {Component} from 'vue-property-decorator';
    import {parse} from '@typescript-eslint/parser';
    import hashCode from '@/libs/hashCode';
    import dayjs from 'dayjs';

    @Component({
        components: {
            Type,
            Amount,
            Category,
            Notes,
            NumberPad,
            DatePicker
        },
        mounted() {
            this.$store.commit('fetchRecords');
        }
    })
    export default class Tally extends Vue {
        name = 'Tally';
        type = '-';                 // '-'表示支出,'+'表示收入
        numbers: number[] = [];     // 保存旧值
        oldValue = '';              // 上次点击加号之前的值
        newValue = '';              // 当前正在输入的值
        firstContent = true;        // 要输入的是否是首个字符
        hasDot = false;             // 当前数字部分是否已有小数点
        selectedCategory = '';      // 提交的类别
        notes = '';         // 提交的备注
        selectedDate = dayjs().format('YYYY-MM-DD');

        // 当前总金额(字符串)
        get amountValue(): string {
            if (this.oldValue === '' || parseFloat(this.oldValue) === 0) {
                // 首个值
                return this.newValue;
            } else {
                const number = (parseFloat(this.oldValue) || 0) + (parseFloat(this.newValue) || 0);
                return `${number.toFixed(2)}`;   // 取两位精度
            }
        }

        // 当前完整计算表达式(字符串)
        get expression(): string {
            let tempExpression = '';
            this.numbers.forEach((item: number) => {
                tempExpression += item + '+';
            });
            if (this.newValue === '') {
                tempExpression.slice(0, -1);
            }
            return tempExpression + this.newValue;
        }

        // 清空数据
        clearData() {
            this.numbers = [];
            this.oldValue = '';
            this.newValue = '';
            this.firstContent = true;
            this.hasDot = false;
            this.notes = '';
        }

        // 切换选择收入或支出
        selectType(type: string) {
            this.type = type;
            this.clearData();
        }

        // 处理输入的复杂逻辑
        changeAmount(content: string) {
            if (content === '+') {
                this.enterPlusSign();
            } else if (content === '.') {
                this.enterDotSign();
            } else if (content === 'clear') {
                this.clearData();
            } else if (content === 'delete') {
                this.enterDeleteSign();
            } else if (content === 'confirm') {
                this.submitData();
            } else {
                this.enterDigitSign(content);
            }
        }

        // 点击加号button
        enterPlusSign() {
            // 当要输入的是首个字符时，禁止输入'+'
            // 当前字符串末尾字符为'.'时，禁止输入'+'
            if (!this.firstContent) {
                if (parseFloat(this.newValue) === 0) {
                    alert('亲, 0元咱就别往上加了');
                } else {
                    this.hasDot = false;
                    // 计算新数据，存储旧数据
                    this.oldValue = (parseFloat(this.oldValue) || 0) + (parseFloat(this.newValue) || 0) + '';
                    this.numbers.push(parseFloat(this.newValue) || 0);
                    // newValue归零
                    this.newValue = '';
                }
            }
            this.firstContent = true;  // 不能连续输入两个'+'
        }

        // 点击小数点button
        enterDotSign() {
            if (!this.hasDot) {
                if (this.firstContent) {
                    // 当输入的时首个字符时，如果输入'.'，前面自动补0
                    this.newValue += '0' + '.';
                } else {
                    this.newValue += '.';
                }
            }
            this.hasDot = true;
            this.firstContent = false;
        }

        // 点击删除button
        enterDeleteSign() {
            if (parseFloat(this.amountValue) === 0 || this.amountValue === '') {
                this.newValue = '';
                this.firstContent = true;        // 要输入的是否是首个字符
                this.hasDot = false;
            }
            if (this.expression.endsWith('+')) {
                // 马上要输入新的值，提前结束新值输入，滚回旧值
                this.newValue = this.numbers.pop() + '';
                this.oldValue = (parseFloat(this.oldValue) || 0) - (parseFloat(this.newValue) || 0) + '';
            } else if (this.expression.endsWith('.')) {
                this.newValue = this.newValue.slice(0, -1);
                this.hasDot = false;
                if (this.expression.endsWith('0')) {
                    this.newValue = this.newValue.slice(0, -1);
                    this.firstContent = true;
                }
            } else {
                // 当前值去掉最后一位
                this.newValue = this.newValue.slice(0, -1);
            }
        }

        // 点击了数字button
        enterDigitSign(content: string) {
            // 小数点后已有两位，不可再增加
            if (this.newValue.slice(-3, -2) !== '.') {
                if (content === '0') {
                    if (!this.firstContent) {
                        this.newValue += content;
                    }
                } else {
                    this.newValue += content;
                    this.firstContent = false;
                }
            }
        }

        // 点击确定button，提交数据
        submitData() {
            if (parseFloat(this.amountValue) === 0 || this.amountValue === '') {
                alert('亲, 0元咱就别记了');
            } else {
                const record: RecordItem = {
                    type: this.type,
                    amount: parseFloat(this.amountValue),
                    category: this.selectedCategory,
                    notes: this.notes,
                    time: (dayjs(this.selectedDate).isSame(dayjs(), 'day') ? dayjs() : dayjs(this.selectedDate)).toISOString(),
                    hashCode: 0
                };
                this.$store.commit('createRecord', record);
                alert('记了一笔账, 好开森!');
                this.clearData();
            }
        }
    }
</script>

<style lang="scss">
    .tally-wrapper {
    }

    .tally-content {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
    }

    .tally-operations {
        flex-grow: 1;
        overflow: auto;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
    }


</style>

<style lang="scss" scoped>

</style>